<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/3/13 0013
 * Time: 18:12
 */
namespace app\admin\controller;
use app\models\Bases;
use think\Controller;

class Login extends Controller{
    /**
     * 后台登录
     * */
    public function login(){
        if(request()->isPost()){
            $post  = input('param.');
            $admin = new Bases('admin');
            try{
                // 登录场景验证
                $validate = $this->validate($post,'User.login');
                if(true !== $validate){
                    throw new \LogicException($validate,1000);
                }
                // 登录验证
                $info = $this->check($post);

                // 记录cookie
                isset($post['remember']) ? cookie('login',$info['id'],3600 * 7) : cookie('login',$info['id'],3600);
                // 清空登录失败次数
                session('fail_times',null);

                // 更新用户登陆信息
                $save['id']              = $info['id'];
                $save['last_login_time'] = time();
                $save['last_login_ip']   = ip2long($_SERVER["REMOTE_ADDR"]);
                $save['login_times']     = ['exp','login_times+1'];
                $bool  = $admin->updateData($save);
                $bool1 = $admin->addAdminLog('登录');
                if(!$bool || !$bool1){
                    throw new \LogicException('登录失败',1001);
                }
            } catch (\LogicException $e){
                return self::result($e->getCode(),$e->getMessage());
            }
            return self::result(0,'登录成功');
        } else {
            $config = new Bases('config');
            $config['system_name']    = $config->value(['cname' => 'system_name'],'option');
            $config['system_version'] = $config->value(['cname' => 'system_version'],'option');
            $config['copyright']      = $config->value(['cname' => 'copyright'],'option');
            return view('login',['config'=>$config]);
        }
    }

    /**
     * 登录验证
     * @param $post
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @throws \Exception
     */
    protected function check($post){
        $admin = new Bases('admin');
        $info = $admin->find(['username'=>$post['username']]);
        // 验证用户状态
        if($info['status'] == $admin::STATUS_OFF){
            throw new \LogicException('账号已锁定',1002);
        }
        // 读取配置文件判断登录失败是否达到最大
        $config = new Bases('config');
        $max_fails = $config->value(['cname' => 'max_login_fails'],'option');
        $isLogin = session('?fail_times') ? (empty($max_fails) ? true : (session('fail_times') < $max_fails ? true : false)) : true;
        if(!$isLogin && !$max_fails){
            // 登录失败达到上限后，锁定用户
            $admin->setField(['id'=>$info['name']],['status'=>$admin::STATUS_OFF]);
            throw new \LogicException('登录失败次数过多',1003);
        }
        // 验证密码
        $bool = password_verify($post['password'],$info['password']);
        if(!$bool){
            if($max_fails){
                // 记录当天登录失败次数
                $life = strtotime(date('Y-m-d',strtotime(date('Y-m-d').'+1 day'))) - time();
                if(!session('fail_times')){
                    session(['name'=>'fail_times','expire'=>$life]);
                    session('fail_times',1);
                } elseif(session('fail_times') < $max_fails) {
                    $i = session('fail_times');
                    $i += 1;
                    session('fail_times',$i);
                }
            }
            throw new \LogicException('登录失败',1001);
        }
        return $info;
    }

    /**
     * 退出
     * */
    public function logout(){
        cookie('login',null);
        $this->redirect('login/login');
    }

    /**
     * login控制器空方法
     * */
    public function _empty(){
        return view('Error/404');
    }
}
